package com.jingdun.sport.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.jingdun.sport.api.config.ApiConfig;
import com.jingdun.sport.api.constants.CommonConstrants;
import com.jingdun.sport.api.helper.CommonsHelper;
import com.jingdun.sport.bean.app.param.BindMobile;
import com.jingdun.sport.bean.app.param.BindWeixin;
import com.jingdun.sport.bean.app.param.RegisterMobile;
import com.jingdun.sport.bean.app.param.RegisterWeixin;
import com.jingdun.sport.bean.enums.SmsType;
import com.jingdun.sport.bean.model.LoginMobile;
import com.jingdun.sport.bean.model.LoginWeixin;
import com.jingdun.sport.bean.model.User;
import com.jingdun.sport.common.constants.RedisConstants;
import com.jingdun.sport.common.util.RedisUtil;
import com.jingdun.sport.dao.LoginMobileMapper;
import com.jingdun.sport.dao.LoginWeixinMapper;
import com.jingdun.sport.dao.UserMapper;
import com.jingdun.sport.security.exception.WxErrorExceptionBase;
import com.jingdun.sport.security.service.YamiUser;
import com.jingdun.sport.security.util.SecurityUtils;
import com.jingdun.sport.service.UserAuthService;
import com.jingdun.sport.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Service
@Slf4j
@AllArgsConstructor
public class UserAuthServiceImpl extends ServiceImpl<UserMapper, User> implements UserAuthService {
    @Autowired
    private UserService userService;

    @Autowired
    private LoginMobileMapper loginMobileMapper;

    @Autowired
    private LoginWeixinMapper loginWeixinMapper;

    @Autowired
    private ApiConfig apiConfig;

    private boolean checkMobile(String mobile) {
        LambdaQueryWrapper<LoginMobile> mobileQueryWrapper = new LambdaQueryWrapper<LoginMobile>()
                .eq(LoginMobile::getMobile, mobile);
        Integer count = loginMobileMapper.selectCount(mobileQueryWrapper);
        return count == 0;
    }

    @Override
    public void bindMobile(BindMobile bindMobile, String user) {
        String correctCode = RedisUtil.get(SmsType.VALID.value() + RedisConstants.PhoneCode + bindMobile.getMobile());
        if (!bindMobile.getMobileCode().equals(correctCode)) {
            throw new WxErrorExceptionBase("验证码异常");
        }
        if (!checkMobile(bindMobile.getMobile())) {
            throw new WxErrorExceptionBase("该手机号已使用");
        }
        LoginMobile loginMobile = new LoginMobile();
        loginMobile.setMobile(bindMobile.mobile);
        loginMobile.setUser(user);
        if (!SqlHelper.retBool(loginMobileMapper.insert(loginMobile))) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
    }

    @Override
    public User registerMobile(RegisterMobile registerMobile) {
        String correctCode = RedisUtil.get(SmsType.REGISTER.value() + RedisConstants.PhoneCode + registerMobile.getMobile());
        if (!registerMobile.getMobileCode().equals(correctCode)) {
            throw new WxErrorExceptionBase("验证码异常");
        }
        if (!checkMobile(registerMobile.getMobile())) {
            throw new WxErrorExceptionBase("该手机号已使用");
        }

        User user = new User();
        Date nowDate = new Date();
        String ip = CommonsHelper.getCliectIp(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        user.setUserLastip(ip);
        user.setUserLasttime(nowDate);
        user.setUserId(RandomUtil.randomString(CommonConstrants.UserIdRandomCount));
        user.setUserMobile(registerMobile.getMobile());
        user.setRealName(registerMobile.getMobile());
        user.setNickName(registerMobile.getMobile());
        user.setStatus(CommonConstrants.UserStatus_1);
        user.setUserRegip(ip);
        user.setUserRegtime(nowDate);
        user.setPic(apiConfig.getFile_default_url());
        user.setModifyTime(nowDate);
        user.setScore(CommonConstrants.UserIdInitScore);
        if (!userService.save(user)) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
        LoginMobile loginMobile = new LoginMobile();
        loginMobile.setMobile(registerMobile.getMobile());
        loginMobile.setUser(user.getUserId());
        if (!SqlHelper.retBool(loginMobileMapper.insert(loginMobile))) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
        return user;
    }

    private boolean checkUnionId(String unionId) {
        LambdaQueryWrapper<LoginWeixin> unionIdQueryWrapper = new LambdaQueryWrapper<LoginWeixin>()
                .eq(LoginWeixin::getUnionId, unionId);
        Integer count = loginWeixinMapper.selectCount(unionIdQueryWrapper);
        return count == 0;
    }

    @Override
    public void bindWeixin(BindWeixin bindWeixin, String user) {
        if (!checkMobile(bindWeixin.getUnionId())) {
            throw new WxErrorExceptionBase("该微信号已使用");
        }
        LoginWeixin loginMobile = new LoginWeixin();
        loginMobile.setOpenId(bindWeixin.getOpenId());
        loginMobile.setUnionId(bindWeixin.getUnionId());
        loginMobile.setUser(user);
        if (!SqlHelper.retBool(loginWeixinMapper.insert(loginMobile))) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
    }

    @Override
    public User registerWeixin(RegisterWeixin registerWeixin) {
        Date wxnowDate = new Date();
        String wxip = CommonsHelper.getCliectIp(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User user = new User();
        user.setUserLastip(wxip);
        user.setUserLasttime(wxnowDate);
        user.setUserId(RandomUtil.randomString(CommonConstrants.UserIdRandomCount));
        user.setRealName(registerWeixin.getNickname());
        user.setNickName(registerWeixin.getNickname());
        user.setStatus(CommonConstrants.UserStatus_1);
        user.setUserRegip(wxip);
        user.setUserRegtime(wxnowDate);
        user.setPic(registerWeixin.getHeadImg());
        user.setModifyTime(wxnowDate);
        user.setScore(CommonConstrants.UserIdInitScore);
        if (!userService.save(user)) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
        LoginWeixin loginWeixin = new LoginWeixin();
        loginWeixin.setOpenId(registerWeixin.getOpenId());
        loginWeixin.setUnionId(registerWeixin.getUnionId());
        loginWeixin.setUser(user.getUserId());
        if (!SqlHelper.retBool(loginWeixinMapper.insert(loginWeixin))) {
            throw new WxErrorExceptionBase("新增用户异常。");
        }
        return user;
    }
}
